#compdef pandoc

# {{{ helper: cache policy for available formats and other variables
(( $+functions[__pandoc_cache_policy] )) ||
__pandoc_cache_policy(){
  local cache_file="$1"
  if [[ -f "${commands[pandoc]}" && -f "${cache_file}" ]]; then
    # if the manifest file is newer then the cache:
    if [[ "${commands[pandoc]}" -nt "${cache_file}" ]]; then
      return 0
    else
      return 1
    fi
  else
    return 0
  fi
}
# }}}
# {{{ choose a format among supported output format
(( $+functions[_pandoc_output_format] )) ||
_pandoc_output_format(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  if _cache_invalid pandoc_output_formats_simple; then
    output_formats_simple=($(pandoc --list-output-formats))
    _store_cache pandoc_output_formats_simple output_formats_simple
  else
    _retrieve_cache pandoc_output_formats_simple
  fi
  if _cache_invalid pandoc_output_formats_plus_extensible || _cache_invalid pandoc_output_formats_minus_extensible; then
    for f in ${output_formats_simple[*]}; do
      for e in $(pandoc --list-extensions=${f}); do
        if [[ "${e}" =~ '^\+' ]]; then
          output_formats_plus_extensible+=("${f}${e}")
        elif [[ "${e}" =~ '^\-' ]]; then
          output_formats_minus_extensible+=("${f}${e}")
        fi
      done
    done
    _store_cache pandoc_output_formats_minus_extensible output_formats_minus_extensible
    _store_cache pandoc_output_formats_plus_extensible output_formats_plus_extensible
  else
    _retrieve_cache pandoc_output_formats_minus_extensible
    _retrieve_cache pandoc_output_formats_plus_extensible
  fi
  _alternative \
    'formats_plus:format:{_multi_parts "+" output_formats_plus_extensible}' \
    'formats_minus:format:{_multi_parts -- "-" output_formats_minus_extensible}'
}
# }}}
# {{{ choose a format among supported input format
(( $+functions[_pandoc_input_format] )) ||
_pandoc_input_format(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  if _cache_invalid pandoc_input_formats_simple; then
    input_formats_simple=($(pandoc --list-input-formats))
    _store_cache pandoc_input_formats_simple input_formats_simple
  else
    _retrieve_cache pandoc_input_formats_simple
  fi
  if _cache_invalid pandoc_input_formats_plus_extensible || _cache_invalid pandoc_input_formats_minus_extensible; then
    for f in ${input_formats_simple[*]}; do
      for e in $(pandoc --list-extensions=${f}); do
        if [[ "${e}" =~ '^\+' ]]; then
          input_formats_plus_extensible+=("${f}${e}")
        elif [[ "${e}" =~ '^\-' ]]; then
          input_formats_minus_extensible+=("${f}${e}")
        fi
      done
    done
    _store_cache pandoc_input_formats_minus_extensible input_formats_minus_extensible
    _store_cache pandoc_input_formats_plus_extensible input_formats_plus_extensible
  else
    _retrieve_cache pandoc_input_formats_minus_extensible
    _retrieve_cache pandoc_input_formats_plus_extensible
  fi
  _alternative \
    'formats_plus:format:{_multi_parts "+" input_formats_plus_extensible}' \
    'formats_minus:format:{_multi_parts -- "-" input_formats_minus_extensible}'
}
# }}}
# {{{ choose a format among all supported formats
(( $+functions[_pandoc_all_formats] )) ||
_pandoc_all_formats(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  if _cache_invalid pandoc_input_formats_simple; then
    input_formats_simple=($(pandoc --list-input-formats))
    _store_cache pandoc_input_formats_simple input_formats_simple
  else
    _retrieve_cache pandoc_input_formats_simple
  fi
  if _cache_invalid pandoc_output_formats_simple; then
    output_formats_simple=($(pandoc --list-output-formats))
    _store_cache pandoc_output_formats_simple output_formats_simple
  else
    _retrieve_cache pandoc_output_formats_simple
  fi
  if _cache_invalid pandoc_all_formats; then
    all_formats=(${output_formats_simple} ${input_formats_simple})
    all_formats=($(sort -u <<<"${all_formats[*]}"))
    _store_cache pandoc_all_formats all_formats
  else
    _retrieve_cache pandoc_all_formats
  fi
  _describe "format" all_formats
}
# }}}
# {{{ pdf engine choice
(( $+functions[_pandoc_pdf_engine] )) ||
_pandoc_pdf_engine(){
  _alternative \
    'engines:engine:{_values "engine" pdflatex lualatex xelatex wkhtmltopdf weasyprint prince context pdfroff}' \
    'engine_files:engine:_files'
}
# }}}
# {{{ options to pass to --pdf-engine command
(( $+functions[_pandoc_pdf_engine_opts] )) ||
_pandoc_pdf_engine_opts(){
  local pdf_engine=${opt_args[--pdf-engine]}
  case ${pdf_engine} in
    "pdflatex"|"lualatex"|"xelatex"|"xetex"|"latex"|"pdftex"|"tex"|"")
      _tex
      ;;
    *)
      type _${pdf_engine} > /dev/null
      if [[ $? == 1 ]]; then
        _message "Options for ${pdf_engine}"
      fi
      ;;
  esac
}
# }}}
# {{{ choose data-dir
(( $+functions[_pandoc_data_dir] )) ||
_pandoc_data_dir(){
  _files -/
}
# }}}
# {{{ choose template from data-dir
(( $+functions[_pandoc_template] )) ||
_pandoc_template(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  if _cache_invalid pandoc_output_formats_simple; then
    output_formats_simple=($(pandoc --list-output-formats))
    _store_cache pandoc_output_formats_simple output_formats_simple
  else
    _retrieve_cache pandoc_output_formats_simple
  fi
  local data_dir=${opt_args[--data-dir]}
  if [[ -z $data_dir ]]; then
    if _cache_invalid pandoc_default_data_dir; then
      default_data_dir=$(pandoc --version | sed -ne 's/Default user data directory: \(.*\)/\1/p')
      _store_cache pandoc_default_data_dir default_data_dir
    else
      _retrieve_cache pandoc_default_data_dir
    fi
    data_dir=${default_data_dir}
  fi
  _pandoc_template_find_args="-name '*.'${output_formats_simple[1]}"
  for ((i = 2; i < ${#output_formats_simple[@]}; i++ )); do
    _pandoc_template_find_args=$_pandoc_template_find_args" -or -name '*.'${output_formats_simple[$i]}"
  done
  templates=($(eval find -L ${data_dir}/templates ${_pandoc_template_find_args} 2>/dev/null | sed -e 's/.*\///' -e 's/\.[^.]*$//'))
  if [[ -z "${templates}" ]]; then
    templates=default
  fi
  _describe 'templates from default data-dir' templates
}
# }}}
# {{{ choose highlight-style
(( $+functions[_pandoc_highlight_style] )) ||
_pandoc_highlight_style(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  if _cache_invalid pandoc_highlighting_styles; then
    highlighting_styles=($(pandoc --list-highlight-styles))
    _store_cache pandoc_highlighting_styles highlighting_styles
  else
    _retrieve_cache pandoc_highlighting_styles
  fi
  _alternative \
    'styles:style:{_values "syntax builting style" ${highlighting_styles[*]}}' \
    'style_files_here:style:{_files -g "*.theme"}'
}
# }}}
# {{{ choose filter from specified or default data-dir
(( $+functions[_pandoc_filter] )) ||
_pandoc_filter(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  local data_dir=${opt_args[--data-dir]}
  if [[ -z $data_dir ]]; then
    if _cache_invalid pandoc_default_data_dir; then
      default_data_dir=$(pandoc --version | sed -ne 's/Default user data directory: \(.*\)/\1/p')
      _store_cache pandoc_default_data_dir default_data_dir
    else
      _retrieve_cache pandoc_default_data_dir
    fi
    data_dir=${default_data_dir}
  fi
  local filters_dir=$data_dir"/filters"
  _alternative \
    'local_filter:filter:{_files -g "*.lua"}' \
    'data_dir_filter:filter:{_files -W filters_dir -g "*.lua"}'
}
# }}}
# {{{ choose lua filter from specified or default data-dir
(( $+functions[_pandoc_lua_filter] )) ||
_pandoc_lua_filter(){
  local update_policy
  zstyle -s ":completion:${curcontext}:" cache-policy update_policy
  if [[ -z "$update_policy" ]]; then
    zstyle ":completion:${curcontext}:" cache-policy __pandoc_cache_policy
  fi
  local data_dir=${opt_args[--data-dir]}
  if [[ -z $data_dir ]]; then
    if _cache_invalid pandoc_default_data_dir; then
      default_data_dir=$(pandoc --version | sed -ne 's/Default user data directory: \(.*\)/\1/p')
      _store_cache pandoc_default_data_dir default_data_dir
    else
      _retrieve_cache pandoc_default_data_dir
    fi
    data_dir=${default_data_dir}
  fi
  local filters_dir=$data_dir"/filters"
  _alternative \
    'local_filter:filter:{_files -g "(#q*)(.)"}' \
    'data_dir_filter:filter:{_files -W filters_dir -g "(#q*)(.)"}'
  }
# }}}
# {{{ choose reference location
(( $+functions[_pandoc_reference_location] )) ||
_pandoc_reference_location(){
  local -a policies
  policies=(
    'block:place references at the end of the current (top-level) block'
    'section:place references at the end of the current (top-level) section'
    'document:place references at the end of the document'
  )
  _describe 'location' policies
}
# }}}
# --base-header-level must be 1-5: https://github.com/jgm/pandoc/blob/34d8ffbcfc33b86766ff7229be4d8a0d1fbffb50/src/Text/Pandoc/App.hs#L867
# {{{ choose top level division
(( $+functions[_pandoc_top_level_division] )) ||
_pandoc_top_level_division(){
  _values 'top level division' default section chapter part
}
# }}}
# {{{ choose header levels
(( $+functions[_pandoc_header_levels] )) ||
_pandoc_header_levels(){
  _values -s , "number" 1 2 3 4 5 6
}
(( $+functions[_pandoc_header_level] )) ||
_pandoc_header_level(){
  _values "number" 1 2 3 4 5 6
}
# }}}
# {{{ choose email obfusication
(( $+functions[_pandoc_email_obfusication] )) ||
_pandoc_email_obfusication(){
  local -a policies
  policies=(
    'none:(default) leaves mailto: links as they are'
    'javascript:obfuscates them using JavaScript'
    'references:obfuscates them by printing their letters as decimal or hexadecimal character references'
  )
  _describe 'obfusication' policies
}
# }}}
# {{{ choose wrapping policy
(( $+functions[_pandoc_wrap] )) ||
_pandoc_wrap() {
  local -a policies
  policies=(
    'auto:(default) wrap lines to the column width specified by --columns (default 72)'
    "none:don't wrap lines at all"
    'preserve:attempt to preserve the wrapping from the source document'
  )
  _describe 'policy' policies
}
# }}}
# {{{ choose eol policy
(( $+functions[_pandoc_eol] )) ||
_pandoc_eol() {
  local -a policies
  policies=(
    'native:line endings appropriate to the OS on which pandoc is being run'
    'crlf:windows'
    'lf:macOS/Linux/UNIX'
  )
  _describe 'policy' policies
}
# }}}
# {{{ choose changes tracking policy
(( $+functions[_pandoc_track_changes] )) ||
_pandoc_track_changes() {
  local -a policies
  policies=(
    'accept:(default) inserts all insertions, and ignores all deletions'
    'reject:inserts all deletions and ignores insertions'
    'all:puts in insertions, deletions, and comments, wrapped in spans with insertion, deletion, comment-start, and comment-end classes, respectively'
  )
  _describe 'policy' policies
}
# }}}

# The real thing
_arguments -C \
  {-f,-r,--from=,--read=}'[specify input format]:format:_pandoc_input_format' \
  {-t,-w,--to=,--write=}'[specify output format]:format:_pandoc_output_format' \
  {-o,--output=}'[write output to FILE instead of stdout]:file:_files' \
  '--data-dir=[specify the user data directory to search for pandoc data files]:dir:_pandoc_data_dir' \
  '--base-header-level=[specify the base level for headers (defaults to 1)]:number:_pandoc_header_level' \
  '--strip-empty-paragraphs[deprecated. Use the +empty_paragraphs extension instead]: :' \
  '--indented-code-classes=[classes to use for indented code blocks]:class:{_message "Classes separated with ,"}' \
  '*--filter=[specify an executable to be used as a filter transforming the pandoc AST after the input is parsed and before the output is written]:file:_pandoc_filter' \
  '*--lua-filter=[transform the document in a similar fashion as JSON filters (see --filter), but use pandoc'"'"'s built-in lua filtering system]:file:_pandoc_lua_filter' \
  {-p,--preserve-tabs}'[preserve tabs instead of converting them to spaces]: :' \
  '--tab-stop=[specify the number of spaces per tab (default is 4)]:number:{_message -r "choose a number equals to or greater then 1"}' \
  '--track-changes=[specifies what to do with insertions, deletions, and comments produced by the MS Word "Track Changes" feature]: :_pandoc_track_changes' \
  '--file-scope[parse each file individually before combining for multifile documents]: :' \
  '--extract-media=[extract images and other media contained in or linked from the source document to the path DIR]:dir:{_dir_list}' \
  {-s,--standalone}'[produce output with an appropriate header and footer]: :' \
  '--template=[use FILE as a custom template for the generated document. Implies --standalone]: :_pandoc_template' \
  {\*-M,\*--metadata=}'[set the metadata field KEY to the value VALUE]:key\:value: ' \
  {\*-V,\*--variable=}'[set the variable KEY to the value VALUE]:key\:value: ' \
  '(- :)'{-D,--print-default-template=}'[print the system default template for an output]:format:_pandoc_output_format' \
  '(- :)--print-default-data-file=[print a system default data file]:file: ' \
  '(- :)--print-highlight-style=[prints a JSON version of a highlighting style]:style|file: ' \
  '--dpi=[specify the dpi (dots per inch) value for conversion from pixels to inch/centimeters and vice versa]:number: ' \
  '--eol=[manually specify line endings (crlf|lf|native)]: :_pandoc_eol' \
  '--wrap=[determine how text is wrapped in the output (the source code, not the rendered version)]: :_pandoc_wrap ' \
  '--columns=[specify length of lines in characters (default 72)]:number: ' \
  '--strip-comments[strip out HTML comments in the Markdown or Textile source]: : ' \
  {--toc,--table-of-contents}'[include an automatically generated table of contents]: : ' \
  '--toc-depth=[specify the number of section levels to include in the table of contents]:number:{_message -r "choose a number equals to or greater then 1"}' \
  '--no-highlight[disables syntax highlighting for code blocks and inlines]: : ' \
  '--highlight-style=[specifies the coloring style to be used in highlighted source code]:style|file:_pandoc_highlight_style' \
  '--syntax-definition=[load a KDE XML syntax definition file]:file:{_files -g "*.xml"}' \
  {\*-H,\*--include-in-header=}'[include contents of FILE, verbatim, at the end of the header, implies --standalone]:file:_files' \
  {\*-B,\*--include-before-body=}'[include contents of FILE, verbatim, at the beginning of the document body, implies --standalone]:file:_files' \
  {\*-A,\*--include-end-body=}'[include contents of FILE, verbatim, at the end of the document body, implies --standalone]:file:_files' \
  '--resource-path=[list of paths to search for images and other resources]:searchpath:_dir_list' \
  '--request-header=[set the request header NAME to the value VAL when making HTTP requests]:name\:val: ' \
  '--self-contained[produce a standalone HTML file with no external dependencies, using data: URIs to incorporate the contents of linked scripts, stylesheets, images, and videos. Implies --standalone]: : ' \
  '--html-q-tags[use <q> tags for quotes in HTML]: : ' \
  '--ascii[use only ASCII characters in output, supported only for HTML and DocBook output]: : ' \
  '--reference-links[use reference-style links, rather than inline links]: : ' \
  '--reference-location=[specify where footnotes (and references, if reference-links is set) are placed (block|section|document)]: :_pandoc_reference_location' \
  '--atx-headers[use ATX-style headers in Markdown and AsciiDoc output]: : ' \
  '--top-level-division=[treat top-level headers as the given division type in LaTeX, ConTeXt, DocBook, and TEI output]: :_pandoc_top_level_division' \
  {-N,--number-sections}'[number section headings in LaTeX, ConTeXt, HTML, or EPUB output]: : ' \
  '--number-offset=[offset for section headings in HTML output (ignored in other output formats)]: :_pandoc_header_levels' \
  '--listings[use the listings package for LaTeX code blocks]: : ' \
  {-i,--incremental}'[make list items in slide shows display incrementally (one by one)]: : ' \
  '--slide-level=[specifies that headers with the specified level create slides (for beamer, s5, slidy, slideous, dzslides)]: :_pandoc_header_levels' \
  '--section-divs[wrap sections in <section> tags (or <div> tags for html4)Use the section-divs package for LaTeX code blocks]: : ' \
  '--email-obfusication=[treat top-level headers as the given division type in LaTeX, ConTeXt, DocBook, and TEI output (none|javascript|references)]: :_pandoc_email_obfusication' \
  '--default-image-extension=[specify a default extension to use when image paths/URLs have no extension]:extension: ' \
  '--id-prefix=[specify a prefix to be added to all identifiers and internal links in HTML and DocBook output]:string: ' \
  {-T,--title-prefix=}'[specify STRING as a prefix at the beginning of the title that appears in the HTML header]:string: ' \
  {\*-c,\*--css=}'[link to a CSS style sheet]:url: ' \
  '--reference-doc=[use the specified file as a style reference in producing a docx or ODT file]:file: ' \
  '--epub-subdirectory=[specify the subdirectory in the OCF container that is to hold the EPUB-specific contents]:dir:{_files -/}' \
  '--epub-cover-image=[use the specified image as the EPUB cover]:file:_files' \
  '--epub-metadata=[look in the specified XML file for metadata for the EPUB]:file:{_files -g "*.xml"}' \
  '*--epub-embed-font=[embed the specified font in the EPUB]:file:_files ' \
  '--epub-chapter-level=[specify the header level at which to split the EPUB into separate "chapter" files]:number:_pandoc_header_level' \
  '--pdf-engine=[use the specified engine when producing PDF output]:program:_pandoc_pdf_engine' \
  '*--pdf-engine-opt=[use the given string as a command-line argument to the pdf-engine]:string:_pandoc_pdf_engine_opts' \
  '*--bibliography=[set the bibliography field in the document'"'"'s metadata to FILE]:file:{_files -g "*.{bib,bibtex,copac,json,yaml,enl,xml,wos,medline,mods,ris}"}' \
  '--csl=[set the csl field in the document'"'"'s metadata to FILE]:file:{_files -g "*.csl"}' \
  '--citation-abbreviations=[set the citation-abbreviations field in the document'"'"'s metadata to FILE]:file:_files' \
  '--natbib[use natbib for citations in LaTeX output]' \
  '--biblatex[use biblatex for citations in LaTeX output]' \
  '--mathml[convert TeX math to MathML (in epub3, docbook4, docbook5, jats, html4 and html5)]' \
  '--webtex=[convert TeX formulas to <img> tags that link to an external script that converts formulas to images]::url: ' \
  '--mathjax=[use MathJax to display embedded TeX math in HTML output]::url: ' \
  '--katex=[use KaTeX to display embedded TeX math in HTML output]::url: ' \
  {-m,--latexmathml=,--asciimathml=}'[deprecated. Use the LaTeXMathML script to display embedded TeX math in HTML output]::url: ' \
  '--mimetex=[deprecated. Render TeX math using the mimeTeX CGI script, which generates an image for each TeX formula]::url: ' \
  '--jsmath=[deprecated. Use jsMath (the predecessor of MathJax) to display embedded TeX math in HTML output]::url: ' \
  '--gladtex[deprecated. Enclose TeX math in <eq> tags in HTML output]: : ' \
  '--abbreviations=[specifies a custom abbreviations file]:file:_files ' \
  '--trace[enable tracing]' \
  '--dump-args[print information about command-line arguments to stdout, then exit]' \
  '--ignore-args[ignore command-line arguments (for use in wrapper scripts)]' \
  '--verbose[give verbose debugging output]' \
  '--quiet[suppress warning messages]' \
  '--fail-if-warnings[exit with error status if there are any warnings]' \
  '--log=[write log messages in machine-readable JSON format to FILE]:file:_file' \
  '(- :)--bash-completion[generate a bash completion script]' \
  '(- :)--list-input-formats[list supported input formats, one per line]' \
  '(- :)--list-output-formats[list supported output formats, one per line]' \
  '(- :)--list-extensions=[list supported extensions, one per line, preceded by a + or - indicating whether it is enabled by default in FORMAT]:format:_pandoc_all_formats' \
  '(- :)--list-highlight-languages[list supported languages for syntax highlighting, one per line]' \
  '(- :)--list-highlight-styles[list supported styles for syntax highlighting, one per line]' \
  '(- :)'{-v,--version}'[print version]' \
  '(- :)'{-h,--help}'[print help]' \
  '*:file:_files'
